package cn.zjw.demo.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SpeechRecognizerClient {
    private final ManagedChannel channel;
    private final SpeechRecognizerGrpc.SpeechRecognizerBlockingStub blockingStub;

    public SpeechRecognizerClient(String host, int port) {

        channel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext(true)
                .build();
        blockingStub = SpeechRecognizerGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }


    /**
     * 创建会话信息
     *
     * @param sessionId
     */
    public void createSession(String sessionId) {
        log.info("Will try to create session [" + sessionId + "]...");
        CreateRequest request = CreateRequest.newBuilder().setClientSession(sessionId).build();
        CreateResponse response;
        try {
            response = blockingStub.createSession(request);
        } catch (StatusRuntimeException e) {
            log.info("RPC failed: {}", e.getStatus());
            return;
        }
        log.info("Session: {}, error_code:{}, error_message:{}", response.getClientSession(), response.getErrorCode(), response.getErrorMessage());
    }

    /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting.
     */
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 50051;
        SpeechRecognizerClient client = new SpeechRecognizerClient(host, port);
        try {

            String sessionId = UUID.randomUUID().toString().replaceAll("-", "");
            if (args.length > 0) {
                sessionId = args[0];
            }
            client.createSession(sessionId);
        } finally {
            client.shutdown();
        }
    }

}
